package com.dycx.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dycx.system.dto.AdminRoleDTO;
import com.dycx.system.entity.AdminRoleDO;
import com.dycx.system.mapper.AdminRoleMapper;
import com.dycx.system.service.AdminRoleService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


@Service
@AllArgsConstructor
public class AdminRoleImpl extends ServiceImpl<AdminRoleMapper, AdminRoleDO> implements AdminRoleService {

    /**
     * 添加
     *
     * @param
     * @return
     */
    @Override
    public Boolean insert(AdminRoleDTO adminRoleDto) {
        List<Integer> adminRoleIds = this.getIdArr(adminRoleDto.getAdminId());

        //删除权限
        ArrayList<Integer> delIds = new ArrayList<>();
        adminRoleIds.forEach(roleId -> {
            if (!adminRoleDto.getRoleIds().contains(roleId)) {
                delIds.add(roleId);
            }
        });
        if (delIds.size() > 0) {
            LambdaQueryWrapper<AdminRoleDO> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(AdminRoleDO::getAdminId, adminRoleDto.getAdminId());
            queryWrapper.in(AdminRoleDO::getRoleId, delIds);

            this.remove(queryWrapper);
        }

        //增加权限
        adminRoleDto.getRoleIds().forEach(roleId -> {
            if (!adminRoleIds.contains(roleId)) {
                AdminRoleDO ra = new AdminRoleDO();
                ra.setAdminId(adminRoleDto.getAdminId());
                ra.setRoleId(roleId);

                this.save(ra);
            }
        });

        return true;
    }

    @Override
    public List<Integer> getIdArr(Integer adminId) {
        LambdaQueryWrapper<AdminRoleDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(AdminRoleDO::getId);
        queryWrapper.eq(AdminRoleDO::getAdminId, adminId);

        List<AdminRoleDO> adminRoleList = this.list(queryWrapper);

        return adminRoleList.stream().map(AdminRoleDO::getRoleId).collect(Collectors.toList());
    }

    /**
     * 删除
     *
     * @param
     * @return
     */
    @Override
    public Boolean delete(Integer adminId) {
        LambdaQueryWrapper<AdminRoleDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AdminRoleDO::getAdminId, adminId);

        return this.remove(queryWrapper);
    }
}
